package com.fucking.great.context.engine;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.util.StrUtil;
import groovy.lang.GroovyObject;
import groovy.lang.Script;

import java.util.Map;


public class GroovyClassLoaderCacheEngine extends GroovyClassLoaderEngine{
    // 默认30分钟缓存.
    private static final TimedCache<String, GroovyObject> SCRIPT_CACHE = CacheUtil.newTimedCache( 30 * 60  * 1000);
    /* 减少scriptStr -> fullClassStr 的步骤。  */
    @Override
    public Object engine(String cacheKey, String scriptStr, Map<String, Object> variable, String... importStr) {
        if (StrUtil.isBlank(cacheKey)) {
            cacheKey = scriptStr;
        }
        Object result = null;
        // 存在了，直接使用。
        GroovyObject groovyObject = SCRIPT_CACHE.get(cacheKey);
        if(groovyObject != null ){
            result = this.execMethod(variable,groovyObject);
        }else{
            result = super.engine(cacheKey,scriptStr,variable,importStr);
        }
        return result;
    }
        //
    @Override
    public GroovyObject getGroovyObject(String cacheKey, String scriptStr) {
        if (StrUtil.isBlank(cacheKey)) {
            cacheKey = scriptStr;
        }
        String finalCacheKey = cacheKey;
        return   SCRIPT_CACHE.get(cacheKey, () -> {
            return super.getGroovyObject(finalCacheKey,scriptStr);
        });
    }
}
